package stark.app.function.net_ping_ip;

import stark.app.R;
import stark.app.databinding.ActivityIpCalDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.IpUtil;

/**
 * Author：daizhongbin on 2022/8/30
 * Email：1027154338@qq.com
 * Desc:
 */
public class IpCalDemoActivity extends BaseNoModelActivity<ActivityIpCalDemoBinding> {
    @Override
    protected int onCreate() {
        return R.layout.activity_ip_cal_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnIpMask.setOnClickListener(v -> {
            clickIpMask();
        });
        mDataBinding.btnMaskIp.setOnClickListener(v -> {
            clickMaskIp();
        });
        mDataBinding.btnMaskCount2Mask.setOnClickListener(v -> {
            clickMaskCount2Mask();
        });
        mDataBinding.btnMask2MaskCount.setOnClickListener(v -> {
            clickMask2MaskCount();
        });
    }

    @Override
    protected void initData() {
    }

    private void clickIpMask() {
        IpUtil.IpMaskInfo maskInfo = IpUtil.ipMask("192.168.1.1", 8);
        if (maskInfo == null) return;

        StringBuilder builder = new StringBuilder();
        builder.append("执行结果为：\n");
        builder.append("子网掩码：" + maskInfo.mask + "\n\n");
        builder.append("起始IP地址：" + maskInfo.startIp + "\n\n");
        builder.append("结束IP地址：" + maskInfo.broadcastIp + "\n\n");
        builder.append("第一个可用IP地址：" + maskInfo.firstUseIp + "\n\n");
        builder.append("最后一个可用IP地址：" + maskInfo.lastUseIp + "\n\n");
        builder.append("可用IP地址数量：" + maskInfo.usableIpCount + "\n\n");

        mDataBinding.tvRet.setText(builder.toString());
    }

    private void clickMaskIp() {
        String[] startEndIps = IpUtil.getIpRangeByMask("192.168.1.1", "255.255.255.0");
        if (startEndIps == null) return;

        StringBuilder builder = new StringBuilder();
        builder.append("执行结果为：\n");
        builder.append("起始IP地址：" + startEndIps[0] + "\n\n");
        builder.append("结束IP地址：" + startEndIps[1] + "\n\n");

        mDataBinding.tvRet.setText(builder.toString());
    }

    private void clickMaskCount2Mask() {
        String maskIp = IpUtil.getMaskByMaskCount(8);
        mDataBinding.tvRet.setText("执行结果为：\n8位码位对应的子网掩码为：" + maskIp);
    }

    private void clickMask2MaskCount() {
        int maskCount = IpUtil.getMaskCountByMask("255.255.0.0");

        mDataBinding.tvRet.setText("执行结果为：\n255.255.0.0字网掩码的码位数为：" + maskCount);
    }

}
